package com.shujia.data_safe.lock_;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicket implements Runnable {
    private int num;
    private Lock lock = new ReentrantLock();


    public static void main(String[] args) {
        SaleTicket st = new SaleTicket();
        st.num = 100;

        for (int i = 1; i <= 5; i++) {
            new Thread(st, "窗口" + i).start();
        }
    }


    @Override
    public void run() {
        while (num > 0) {
            try {
                // 加锁
                lock.lock();
                if (num > 0) {
                    // 进来了一个线程
                    System.out.println(Thread.currentThread().getName() + ":售出第" + num + "张票");
                    num--;
                    // 。。。。
                    try {
                        // sleep方法不会释放锁。
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } finally {
                // 释放锁
                lock.unlock();

            }
        }
    }

}
